// ignore_for_file: non_constant_identifier_names
import 'package:flutter/material.dart';
import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';
import 'package:get/get.dart';
import 'common.dart';

// 关闭当前的正在加载...
dismissLoading() async {
  await SmartDialog.dismiss(status: SmartStatus.loading);
}

/// 关闭弹出框
dismissAlertDialog() async {
  await SmartDialog.dismiss();
}

showLoadingMessage(String message) async {
  const time = Duration(seconds: 20);
  await SmartDialog.showLoading(msg: message, displayTime: time, usePenetrate: false);
  // await Future.delayed(const Duration(seconds: 1));
  // SmartDialog.dismiss(status: SmartStatus.loading);
}

// 提示
showMessage(String message) {
  double charDisplayTime = 0.15;
  int displayTime = (message.length * charDisplayTime).ceil();
  displayTime = displayTime.clamp(1, 5); // 限制展示时间最小1秒，最大为5秒钟
  SmartDialog.showToast(
    message,
    alignment: const Alignment(0.0, -0.25),
    displayType: SmartToastType.onlyRefresh,
    displayTime: Duration(seconds: displayTime),
    animationType: SmartAnimationType.centerFade_otherSlide,
  );
}

// 提示操作成功
showSuccessMessage(String message) {
  SmartDialog.showNotify(
    msg: message,
    notifyType: NotifyType.success,
    alignment: const Alignment(0.0, -0.25),
    animationType: SmartAnimationType.centerFade_otherSlide,
  );
}

// 提示操作失败
showFailureMessage(String message) {
  double charDisplayTime = 0.2;
  int displayTime = (message.length * charDisplayTime).ceil();
  displayTime = displayTime.clamp(1, 5); // 限制展示时间最小1秒，最大为5秒钟
  SmartDialog.showNotify(
    msg: message,
    notifyType: NotifyType.failure,
    alignment: const Alignment(0.0, -0.25),
    displayTime: Duration(seconds: displayTime),
    animationType: SmartAnimationType.centerFade_otherSlide,
  );
}

// 提示警告！
showAlertMessage(String message) {
  double charDisplayTime = 0.2;
  int displayTime = (message.length * charDisplayTime).ceil();
  displayTime = displayTime.clamp(1, 5); // 限制展示时间最小1秒，最大为5秒钟
  SmartDialog.showNotify(
    msg: message,
    notifyType: NotifyType.alert,
    alignment: const Alignment(0.0, -0.25),
    displayTime: Duration(seconds: displayTime),
    animationType: SmartAnimationType.centerFade_otherSlide,
  );
}

Widget bottomSheetAction(String title, {required VoidCallback onPressed}) {
  return Row(
    children: [
      Expanded(child: TextButton(
        onPressed: onPressed,
        child:  Text(title, style: const TextStyle(fontSize: 15, color: Font_Color_Black_34),))
      ),
    ]
  );
}

// 左右透明 单独取消按钮
show_iOS_bottom_sheet(String title, {List<String>? tags, Map<String, dynamic>? keyValues, required Function onTap}) {
  double height = 0;
  List<Widget> list = [];
  if (keyValues != null) {
    for (String key in keyValues.keys) {
      list.addAll([
        const DividerLine(),
        bottomSheetAction(key, onPressed: () { onTap({key: keyValues[key]}); }),
      ]);
    }
    height = (keyValues.length + 4) * 45;
  }else if (tags != null) {
    for (dynamic item in tags) {
      if (item is String) {
        list.addAll([
          const DividerLine(),
          bottomSheetAction(item, onPressed: () { onTap(item); }),
        ]);
      }
    }
    height = (tags.length + 4) * 45 ;
  }
  Get.bottomSheet(
    barrierColor: Colors.black26,
    isScrollControlled: true,
    Container(
      height: height,
      margin: const EdgeInsets.fromLTRB(30, 0, 30, 0),
      child: Column(
        mainAxisAlignment: MainAxisAlignment.end,
        children: [
          Container(
            decoration: const BoxDecoration(
              color: Colors.white,
              borderRadius: BorderRadius.all(Radius.circular(10)),
            ),
            child: Column(
                children: [
                  const SizedBox(height: 15),
                  Text(title, style: const TextStyle(fontSize: 15, color: Font_Color_grey_153),),
                  const SizedBox(height: 15),
                  Column(
                    children: list,
                  )
                ]
            ),
          ),
          Container(
              margin: const EdgeInsets.fromLTRB(0, 15, 0, 35),
              // padding: const EdgeInsets.fromLTRB(0, 0, 0, 0),
              // height: 400,
              decoration: const BoxDecoration(
                color: Colors.white,
                borderRadius: BorderRadius.all(Radius.circular(10)),
              ),
              child: Row(
                  children: [
                    Expanded(child: TextButton(
                        onPressed: ()=> Get.back(),
                        child: const Text("取消", style: TextStyle(fontSize: 15, color: Font_Color_Black_34, fontWeight: FontWeight.bold),))
                    ),
                  ]
              )
          ),
        ],
      ),
    ),
  );
}


typedef OnData<T> = void Function(T data);
show_bottom_one_selecte(String? title, {required Map<String, num> keyValues, required OnData callback}) {
  Get.bottomSheet(
    StatefulBuilder(builder: (BuildContext context, StateSetter setState) {
      return Container(
        height: 600, color: BGColor_grey_225,
        padding: const EdgeInsets.fromLTRB(0, 0, 0, 0),
        child: Column(
          children: [
            Container(
              color: PageBackgroundColor,
              padding: const EdgeInsets.fromLTRB(0, 10, 0, 10),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Text(title ?? "请选择",
                      textAlign: TextAlign.center,
                      style: const TextStyle(fontSize: 18)),
                ],
              ),
            ),
            const DividerLine(),
            Expanded(
                child: ListView(
                  padding: const EdgeInsets.fromLTRB(0, 10, 0, 0),
                  children: keyValues.keys.map((e) {
                    return Container(
                      color: Colors.white,
                      margin: const EdgeInsets.fromLTRB(0, 0, 0, 0.5),
                      child: ListTile(onTap: ()=>callback({e: keyValues[e]}),
                          title: Text(e, textAlign: TextAlign.center, style: blackStyle())),
                    );
                  }).toList(),
                )
            ),
          ],
        ),
      );
    }),
  );
}


class BottomOneSelectedModel {
  String icon, title, subTitle, value;
  BottomOneSelectedModel({this.icon="", this.title="", this.subTitle="", this.value=""});
}
showBottomOneSelected(String title, List<BottomOneSelectedModel> models, {required Function(BottomOneSelectedModel) callback}) {
  Get.bottomSheet(
      StatefulBuilder(builder: (context, setState) {
        List<Widget> items = [];
        for (var index = 0; index < models.length; index++) {
          BottomOneSelectedModel model = models[index];
          items.add(GestureDetector(
            onTap: ()=> callback(model),
            child: Container(
              color: Colors.white,
              margin: const EdgeInsets.fromLTRB(0, 0, 0, 0.5),
              padding: const EdgeInsets.fromLTRB(15, 12, 15, 12),
              child: Column(
                children: [
                  Row(
                    mainAxisAlignment: (model.icon.isEmpty)
                        ? MainAxisAlignment.center
                        : MainAxisAlignment.start,
                    children: [
                      if (model.icon.startsWith("http")) Padding(
                        padding: const EdgeInsets.fromLTRB(15, 0, 10, 0),
                        child: ImageNetworking(
                          model.icon, width: 44, height: 44,
                          fit: BoxFit.fitHeight,
                        ),
                      ),
                      if (model.icon.isNotEmpty && !(model.icon.startsWith("http"))) Padding(
                        padding: const EdgeInsets.fromLTRB(15, 0, 10, 0),
                        child: ImageAsset(
                          model.icon, width: 44, height: 44,
                          fit: BoxFit.fitHeight,
                        ),
                      ),
                      Text(model.title, style: blackStyle()),

                      if (model.subTitle.isNotEmpty) Row(
                        children: [
                          const SizedBox(width: 10),
                          Text(model.subTitle, style: greyStyle(font: 14)),
                        ],
                      )
                      // const SizedBox(width: 10),
                      // Text(model.subTitle, style: greyStyle(font: 14)),
                    ],
                  ),
                  // if (model.subTitle.isNotEmpty) Row(
                  //   mainAxisAlignment: MainAxisAlignment.center,
                  //   children: [
                  //     Text(model.subTitle, style: greyStyle(font: 14)),
                  //   ],
                  // ),
                ],
              ),
            ),
          ));
        }
        return Container(
          height: 600, color: PageBackgroundColor,
          padding: const EdgeInsets.fromLTRB(0, 0, 0, 0),
          child: Column(
            children: [
              Container(
                color: Colors.white,
                padding: const EdgeInsets.fromLTRB(0, 15, 0, 15),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    Text(title ?? "请选择",
                      textAlign: TextAlign.center,
                      style: greyStyle(font: 18)),
                  ],
                ),
              ),
              const DividerLine(),
              Expanded(child: ListView(
                  padding: const EdgeInsets.fromLTRB(0, 1, 0, 30),
                  children: items
              )),
            ],
          ),
        );
      })
  );
}



show_bottom_one_select2(String? selectTitle, String? imageKey, String? titleKey, String? subTitleKey,
    {required List keyValues, required Function(dynamic) callback}) {
  Get.bottomSheet(
    StatefulBuilder(builder: (BuildContext context, StateSetter setState) {
      List<Widget> list = [];
      var img = "";
      var title = "";
      var subTitle = "";
      for (var index=0; index<keyValues.length; index++) {
        if (keyValues[index].keys.contains(imageKey)) {
          img = keyValues[index][imageKey];
        }
        if (keyValues[index].keys.contains(titleKey)) {
          title = keyValues[index][titleKey];
        }
        if (keyValues[index].keys.contains(subTitleKey)) {
          subTitle = keyValues[index][subTitleKey];
        }
        list.add(
            GestureDetector(
              onTap: ()=> callback(index),
              child: Container(
                height: 50,
                color: Colors.white,
                alignment: Alignment.center,
                margin: const EdgeInsets.fromLTRB(0, 0, 0, 0.5),
                padding: const EdgeInsets.fromLTRB(15, 0, 15, 0),
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    Row(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: [
                        if (img.isNotEmpty && img.startsWith("http")) ImageNetworking(
                          img, width: 35, height: 35,
                          fit: BoxFit.fitHeight,
                        ),
                        Text(title, style: blackStyle()),
                      ],
                    ),
                    const SizedBox(height: 2,),
                    Offstage(
                      offstage: !subTitle.isNotEmpty,
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.center,
                        children: [
                          Text(subTitle, style: greyStyle(font: 14)),
                        ],
                      ),
                    ),
                  ],
                ),
              ),
            )
        );
      }
      return Container(
        height: 600, color: BGColor_grey_225,
        padding: const EdgeInsets.fromLTRB(0, 0, 0, 0),
        child: Column(
          children: [
            Container(
              color: PageBackgroundColor,
              padding: const EdgeInsets.fromLTRB(0, 10, 0, 10),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Text(selectTitle ?? "请选择",
                    textAlign: TextAlign.center,
                    style: const TextStyle(fontSize: 18)),
                ],
              ),
            ),
            const DividerLine(),
            Expanded(child: ListView(children: list)),
          ],
        ),
      );
    }),
  );
}

showAlertDialog({
  String? title,
  String? message,
  InlineSpan? messageTextSpan,
  EdgeInsetsGeometry? margin,
  EdgeInsetsGeometry? padding,
  Widget? content,
  bool? buttonVertical = false,
  bool? hiddenButton = false,
  String? confirmText="确定",
  String? cancelText="取消",
  VoidCallback? confirm,
  VoidCallback? cancel}) async {
  SmartDialog.show(
      clickMaskDismiss: hiddenButton,
      alignment: Alignment.center,
      maskColor: Colors.black54,
      onMask: ()=> FocusManager.instance.primaryFocus?.unfocus(),
      builder: (context) {
        return StatefulBuilder(builder: (BuildContext context, StateSetter setState) {
          return GestureDetector(
            onTap: ()=> FocusManager.instance.primaryFocus?.unfocus(),
            child: Container(
              margin: margin ?? const EdgeInsets.only(left: 30, right: 30, bottom: 130),
              padding: padding ?? const EdgeInsets.all(20),
              decoration: BoxDecoration(color: Colors.white, borderRadius: BorderRadius.circular(20)),
              child: Column(
                mainAxisSize: MainAxisSize.min,
                mainAxisAlignment: MainAxisAlignment.start,
                children: [

                  if (title != null) Padding(
                    padding: const EdgeInsets.only(bottom: 10),
                    child: Text(title??"", style: const TextStyle(fontSize: 20, fontWeight: FontWeight.w500)),
                  ),

                  if (message != null) Padding(
                    padding: const EdgeInsets.only(bottom: 10),
                    child: Text(message??"", style: const TextStyle(fontSize: 16, color: Colors.black, height: 1.5)),
                  ),

                  if (content != null) Padding(
                    padding: const EdgeInsets.only(bottom: 10),
                    child: content,
                  ),

                  if (messageTextSpan != null) Padding(
                    padding: const EdgeInsets.only(bottom: 10),
                    child: RichText(text: messageTextSpan),
                  ),
                  if (hiddenButton == false && buttonVertical == true) Container(
                    padding: const EdgeInsets.fromLTRB(20, 10, 15, 10),
                    child: Column(
                      children: [
                        GradientButton(
                          gradient: const LinearGradient(
                            colors: [Colors.orange, Colors.red, Colors.orange],
                          ),
                          borderRadius: BorderRadius.circular(22),
                          onPressed: confirm ?? ()=> dismissAlertDialog(),
                          child: Text(confirmText!, style: const TextStyle(fontSize: 16, color: Colors.white)),
                        ),
                        const SizedBox(height: 10),
                        MyMaterialButton(
                          color: Colors.transparent,
                          padding: const EdgeInsets.fromLTRB(0, 10, 0, 10),
                          borderRadius: BorderRadius.circular(22),
                          onPressed: cancel ?? ()=> dismissAlertDialog(),
                          child: Text("$cancelText", style: const TextStyle(fontSize: 16, color: Colors.blue))
                        ),
                      ],
                    ),
                  ),
                  if (hiddenButton == false && buttonVertical == false) Container(
                    padding: const EdgeInsets.only(top: 5),
                    child: Row(
                      children: [
                        Expanded(
                          child: TextButton(
                            onPressed: cancel ?? ()=> dismissAlertDialog(),
                            style: ButtonStyle(
                              shape: WidgetStateProperty.all(RoundedRectangleBorder(borderRadius: BorderRadius.circular(18))),
                              // fixedSize: MaterialStateProperty.all(const Size(150, 40)),
                              padding: WidgetStateProperty.all(const EdgeInsets.only(left: 20, right: 20)),
                              side: WidgetStateProperty.all(const BorderSide(width: 0.67, color: Colors.red)),
                              backgroundColor: WidgetStateProperty.all(Colors.transparent)
                            ),
                            child: Text("$cancelText", style: const TextStyle(fontSize: 16,color: Colors.red))
                          ),
                        ),
                        const SizedBox(width: 10),
                        Expanded(
                          child: GradientButton(
                            gradient: const LinearGradient(
                              colors: [Colors.orange, Colors.red],
                            ),
                            borderRadius: BorderRadius.circular(22),
                            onPressed: confirm ?? ()=> dismissAlertDialog(),
                            child: Text(confirmText!, style: const TextStyle(fontSize: 16, color: Colors.white)),
                          ),
                        ),
                      ]
                    ),
                  ),
                ],
              ),
            ),
          );
        });
      });
}

showAlertDialog2({
  String? title,
  String? message,
  String? titleImage = "assets/alert_top.png",
  InlineSpan? messageTextSpan,
  EdgeInsetsGeometry? margin,
  EdgeInsetsGeometry? padding,
  Widget? content,
  bool? buttonVertical = false,
  bool? hiddenButton = false,
  String? confirmText="确定",
  String? cancelText="取消",
  VoidCallback? confirm,
  VoidCallback? cancel}) async {
  SmartDialog.show(
      clickMaskDismiss: hiddenButton,
      alignment: Alignment.center,
      maskColor: Colors.black54,
      onMask: ()=> FocusManager.instance.primaryFocus?.unfocus(),
      builder: (context) {
        return GestureDetector(
          onTap: ()=> FocusManager.instance.primaryFocus?.unfocus(),
          child: Container(
            margin: margin ?? const EdgeInsets.only(left: 30, right: 30, bottom: 130),
            padding: padding ?? const EdgeInsets.all(20),
            decoration: BoxDecoration(
              image: titleImage!=null ? DecorationImage(image: AssetImage(titleImage), alignment: Alignment.topCenter, fit: BoxFit.fitWidth) : null,
              color: Colors.white, borderRadius: BorderRadius.circular(20),
            ),
            child: Column(
              mainAxisSize: MainAxisSize.min,
              mainAxisAlignment: MainAxisAlignment.start,
              children: [

                if (title != null) Padding(
                  padding: EdgeInsets.only(bottom: titleImage!=null ? 30 : 10),
                  child: Text(title??"", style: TextStyle(fontSize: 20, color: titleImage!=null ? Colors.white: Colors.black, fontWeight: FontWeight.w600)),
                ),

                if (message != null) Padding(
                  padding: const EdgeInsets.only(bottom: 10),
                  child: Text(message??"", style: const TextStyle(fontSize: 16, color: Colors.black, height: 1.5)),
                ),

                if (content != null) Padding(
                  padding: const EdgeInsets.only(bottom: 10),
                  child: content,
                ),

                if (messageTextSpan != null) Padding(
                  padding: const EdgeInsets.only(bottom: 10),
                  child: RichText(text: messageTextSpan),
                ),
                if (hiddenButton == false && buttonVertical == true) Container(
                  padding: const EdgeInsets.fromLTRB(20, 10, 15, 10),
                  child: Column(
                    children: [
                      GradientButton(
                        gradient: const LinearGradient(
                          colors: [Colors.orange, Colors.red, Colors.orange],
                        ),
                        borderRadius: BorderRadius.circular(22),
                        onPressed: confirm ?? ()=> dismissAlertDialog(),
                        child: Text(confirmText!, style: const TextStyle(fontSize: 16, color: Colors.white)),
                      ),
                      const SizedBox(height: 15),
                      GestureDetector(
                        onTap: cancel ?? ()=> dismissAlertDialog(),
                        child: Text("$cancelText", style: const TextStyle(fontSize: 16,color: Colors.blue)),
                      ),
                    ],
                  ),
                ),
                if (hiddenButton == false && buttonVertical == false) Container(
                  padding: const EdgeInsets.only(top: 5),
                  margin: const EdgeInsets.fromLTRB(20, 0, 15, 0),
                  child: Row(
                      children: [
                        Expanded(
                          child: TextButton(
                              onPressed: cancel ?? ()=> dismissAlertDialog(),
                              style: ButtonStyle(
                                  shape: WidgetStateProperty.all(RoundedRectangleBorder(borderRadius: BorderRadius.circular(18))),
                                  // fixedSize: MaterialStateProperty.all(const Size(150, 40)),
                                  padding: WidgetStateProperty.all(const EdgeInsets.only(left: 20, right: 20)),
                                  side: WidgetStateProperty.all(const BorderSide(width: 0.67, color: Colors.red)),
                                  backgroundColor: WidgetStateProperty.all(Colors.transparent)
                              ),
                              child: Text("$cancelText", style: const TextStyle(fontSize: 16,color: Colors.red))
                          ),
                        ),
                        const SizedBox(width: 10),
                        Expanded(
                          child: GradientButton(
                            gradient: const LinearGradient(
                              colors: [Colors.orange, Colors.red],
                            ),
                            borderRadius: BorderRadius.circular(22),
                            onPressed: confirm ?? ()=> dismissAlertDialog(),
                            child: Text(confirmText!, style: const TextStyle(fontSize: 16, color: Colors.white)),
                          ),
                        ),
                      ]
                  ),
                ),
              ],
            ),
          ),
        );
      });
}


// 客户关怀->输入客户电话，弹出选择客户列表
showModalBottomSheet1(BuildContext context, List<BottomOneSelectedModel> models, {required Function(BottomOneSelectedModel) callback}) {
  return showModalBottomSheet(
    context: context,
    barrierColor: Colors.black54,
    backgroundColor: Colors.transparent,
    builder: (w) {
        return Column(
          children: [
            Stack(
              children: [
                Padding(
                  padding: const EdgeInsets.fromLTRB(0, 50, 0, 0),
                  child: Container(
                    decoration: const BoxDecoration(
                      color: Colors.white,
                      borderRadius: BorderRadius.only(topLeft: Radius.circular(10), topRight: Radius.circular(10)),
                    ),
                    child: const ImageAsset("assets/select_client_bg.png", fit: BoxFit.fitWidth),
                  ),
                ),
                const Positioned(
                    left: 80, top: 0,
                    child: ImageAsset("assets/select_client_user_icon.png", width: 80, fit: BoxFit.cover)
                ),
              ],
            ),
            Expanded(
              child: Container(
                color: Colors.white,
                margin: const EdgeInsets.fromLTRB(0, 0, 0, 0),
                padding: const EdgeInsets.fromLTRB(0, 10, 0, 10),
                child: ListView.builder(
                    itemCount: models.length,
                    itemBuilder: (context, index) {
                      return MyMaterialButton(
                        delayed: 100,
                        onPressed: ()=> callback(models[index]),
                        child: Column(
                          children: [
                            Container(
                              padding: const EdgeInsets.fromLTRB(15, 15, 0, 15),
                              child: Row(
                                children: [
                                  Text(models[index].title??"", style: blackStyle()),
                                  const SizedBox(width: 15),
                                  Text(models[index].subTitle??"", style: blackStyle()),
                                ],
                              ),
                            ),
                            const DividerLine(),
                          ],
                        ),
                      );
                    }),
              ),
            ),
          ],
        );
      }
  );
}